import numpy as np
import pandas as pd


def data_offset(data, offset=1, fill_value=np.nan):
    """
    获取序列或者
    """
    if isinstance(data, pd.Series):
        tmpSeries = data
        if offset > 0:
            tmpSeries = pd.Series(data=[fill_value] * offset + list(data[0:-offset]), index=data.index)
        elif offset < 0:
            tmpSeries = pd.Series(data=list(data[abs(offset):]) + [fill_value] * abs(offset), index=data.index)
        return tmpSeries
    elif isinstance(data, list):
        tmplist = []
        if offset > 0:
            tmplist = [fill_value] * offset + data[0:-offset]
        elif offset < 0:
            tmplist = data[offset:] + [fill_value] * offset
        return tmplist
    return None


def describe_data_offset(data, offset=-2, fill_value=np.nan, min_offset=-30, cal_max=False, cal_min=False):
    if offset >= -2:
        offset = -1
    if offset <= min_offset:
        offset = min_offset
    t = []
    for i in range(offset, -1, 1):
        t.append(data_offset(data=data, offset=i, fill_value=fill_value))
    arr_t = np.array(t)
    max = None
    min = None
    if cal_max:
        max = arr_t.max(axis=0)
    if cal_min:
        min = arr_t.min(axis=0)
    return max, min






def column_true_false_count(data):
    if isinstance(data, pd.Series):
        true_count = data[data[:]==True].shape[0]
        false_count =data[data[:] ==False].shape[0]
        return (true_count,false_count, data.shape[0])
    return 0,0

def _normfun(x,mu, sigma):
    pdf = np.exp(-((x - mu)**2) / (2* sigma**2)) / (sigma * np.sqrt(2*np.pi))
    return pdf

def normfun(data):
    if isinstance(data, pd.Series):
        try:

            data.replace(np.inf, 0)
            mean = data.mean()
            std = data.std()
            x = np.arange(data.min(), data.max(), 0.01)
            y = _normfun(x, mean, std)
            return x,y,mean,std
        except Exception as e:
            print('计算方差、平均值出错')
            print(e)
            return 0,0,mean,std
    return None


def min_max(data):
    if isinstance(data, list):
        min_data = min(data)
        max_data = max(data)
        return min_data, max_data

# {0: {'1': 2, '2': 1}, 1: {'1': 2, '3': 1, '2': 1}}
# 外层字典表示统计的元素的类别， 里面的字典表示 对应元素出现重复次数的个数
# 例如 0: {'1': 2, '2': 1} 表示 数据集 出现 0 的 情况是 有 1次 连续2天出现0， 有2次 不连续出现0 。 value对应的是连续的次数， key对应是 连续的周期长度

# 出现 X 的 情况统计: 有1次 连续2天出现X， 有2次不连续出现X
def cout_continuous_data(datas, kwargs, need_print=True):
    tmp_datas = None
    if isinstance(datas, pd.Series):
        tmp_datas = list(datas)
    elif isinstance(datas, list):
        tmp_datas = datas
    sta_dic = {}
    for item in kwargs.keys():
        sta_dic[item] = {}

    i = 0
    while i < len(tmp_datas)-1:
        if tmp_datas[i] not in kwargs.keys():
            i +=1
            continue
        repeat_count_key = 1
        count_dic = sta_dic[tmp_datas[i]]
        for j in range(i+1, len(tmp_datas)) :
            if tmp_datas[j]!=tmp_datas[i]:
                if str(repeat_count_key) in count_dic.keys():
                    value = count_dic[str(repeat_count_key)]
                    count_dic[str(repeat_count_key)] = value+1
                else:
                    count_dic[str(repeat_count_key)] = 1
                i = j
                if j == len(datas)-1:
                    last_count_dic = sta_dic[tmp_datas[j]]
                    if str(1) in last_count_dic.keys():
                        value = last_count_dic[str(1)]
                        last_count_dic[str(1)] = value + 1
                    else:
                        last_count_dic[str(1)] = 1
                break
            else:
                i += 1
                repeat_count_key +=1
                #统计只有连续的情况
                if j == len(datas) - 1:
                    count_dic[repeat_count_key] = 1

    content=''
    for key, value in sta_dic.items():
        if key in kwargs.keys() and isinstance(value, dict):
            description = kwargs.get(key)
            content += '###出现 '+description+' 的情况统计###:\n'
            for period, count in value.items():
                if period == '1':
                    content += "有 %d次 间断(不连续，1天有1天没有)出现%s\n"%(count, description)
                else :
                    content += "有 %d次 连续%s天出现%s\n"%(count, period, description)
    if need_print:
        print(content)
    return (sta_dic, content)


# def


# sta_dic, content = cout_continuous_data([1,1,1,1,1,1,1,1,1,1,1,1,1],{1:'上升',0:'下跌', 5:'傻逼'})


# import matplotlib.pyplot as plt
# from pandas import  Series
# acc = Series(data=[0.1,0.2,0.3,0.2,0.18,0.29,0.35])
# x, y = normfun(acc)
# plt.plot(x, y, color='g', linewidth=3)
# # 数据，数组，颜色，颜色深浅，组宽，显示频率
# plt.hist(acc, bins=100, color='r', alpha=0.5, rwidth=0.9, normed=True)
# plt.title(u'内容')
# plt.xlabel(u'偏差值')
# plt.ylabel(u'偏差值分布')
# plt.show()
